package com.monitor.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 浏览器URL监控工具类
 * 用于获取当前活动浏览器窗口的URL
 */
public class BrowserUrlMonitor {
    
    private static final Pattern URL_PATTERN = Pattern.compile(
        "https?://[\\w\\-._~:/?#\\[\\]@!$&'()*+,;=%]+"
    );
    
    /**
     * 获取当前URL（对外接口）
     */
    public static String getCurrentUrl() {
        return getCurrentBrowserUrl();
    }
    
    /**
     * 获取当前活动浏览器窗口的URL
     * 注意：这是一个简化的实现，实际生产环境中需要更复杂的方法
     */
    public static String getCurrentBrowserUrl() {
        try {
            System.out.println("开始获取浏览器URL...");
            
            // 方法1：尝试从Chrome浏览器获取URL
            String chromeUrl = getChromeUrl();
            System.out.println("Chrome URL: " + chromeUrl);
            if (chromeUrl != null && !chromeUrl.isEmpty()) {
                return chromeUrl;
            }
            
            // 方法2：尝试从Edge浏览器获取URL
            String edgeUrl = getEdgeUrl();
            System.out.println("Edge URL: " + edgeUrl);
            if (edgeUrl != null && !edgeUrl.isEmpty()) {
                return edgeUrl;
            }
            
            // 方法3：尝试从Firefox浏览器获取URL
            String firefoxUrl = getFirefoxUrl();
            System.out.println("Firefox URL: " + firefoxUrl);
            if (firefoxUrl != null && !firefoxUrl.isEmpty()) {
                return firefoxUrl;
            }
            
            // 如果都获取不到，返回一个默认的测试URL
            System.out.println("无法获取到浏览器URL，返回默认测试URL");
            return "https://www.example.com";
            
        } catch (Exception e) {
            System.err.println("获取浏览器URL失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return "https://www.example.com";
    }
    
    /**
     * 从Chrome浏览器获取URL
     */
    private static String getChromeUrl() {
        try {
            System.out.println("尝试获取Chrome URL...");
            // 使用PowerShell获取Chrome窗口标题
            ProcessBuilder pb = new ProcessBuilder(
                "powershell.exe", 
                "-Command", 
                "Get-Process chrome -ErrorAction SilentlyContinue | Where-Object {$_.MainWindowTitle -ne ''} | Select-Object MainWindowTitle"
            );
            
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Chrome窗口标题: " + line);
                if (!line.trim().isEmpty() && !line.contains("MainWindowTitle") && !line.contains("---")) {
                    String url = extractUrlFromTitle(line.trim());
                    if (url != null) {
                        System.out.println("从Chrome标题提取的URL: " + url);
                        return url;
                    }
                }
            }
            
            process.waitFor();
            reader.close();
            
        } catch (Exception e) {
            System.err.println("获取Chrome URL失败: " + e.getMessage());
        }
        
        return null;
    }
    
    /**
     * 从Edge浏览器获取URL
     */
    private static String getEdgeUrl() {
        try {
            // 使用PowerShell获取Edge窗口标题
            ProcessBuilder pb = new ProcessBuilder(
                "powershell.exe", 
                "-Command", 
                "Get-Process msedge | Where-Object {$_.MainWindowTitle -ne ''} | Select-Object MainWindowTitle"
            );
            
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            
            String line;
            while ((line = reader.readLine()) != null) {
                String url = extractUrlFromTitle(line);
                if (url != null) {
                    return url;
                }
            }
            
            process.waitFor();
            reader.close();
            
        } catch (Exception e) {
            System.err.println("获取Edge URL失败: " + e.getMessage());
        }
        
        return null;
    }
    
    /**
     * 从Firefox浏览器获取URL
     */
    private static String getFirefoxUrl() {
        try {
            // 使用PowerShell获取Firefox窗口标题
            ProcessBuilder pb = new ProcessBuilder(
                "powershell.exe", 
                "-Command", 
                "Get-Process firefox | Where-Object {$_.MainWindowTitle -ne ''} | Select-Object MainWindowTitle"
            );
            
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            
            String line;
            while ((line = reader.readLine()) != null) {
                String url = extractUrlFromTitle(line);
                if (url != null) {
                    return url;
                }
            }
            
            process.waitFor();
            reader.close();
            
        } catch (Exception e) {
            System.err.println("获取Firefox URL失败: " + e.getMessage());
        }
        
        return null;
    }
    
    /**
     * 从窗口标题中提取URL
     */
    private static String extractUrlFromTitle(String title) {
        if (title == null || title.trim().isEmpty()) {
            System.out.println("标题为空，无法提取URL");
            return null;
        }
        
        System.out.println("正在从标题提取URL: " + title);
        
        // 尝试从标题中匹配URL模式
        Matcher matcher = URL_PATTERN.matcher(title);
        if (matcher.find()) {
            String url = matcher.group();
            System.out.println("通过正则匹配到URL: " + url);
            return url;
        }
        
        // 如果标题包含常见的网站域名，构造URL
        String lowerTitle = title.toLowerCase();
        if (lowerTitle.contains("google")) {
            System.out.println("检测到Google相关标题，返回Google URL");
            return "https://www.google.com";
        } else if (lowerTitle.contains("baidu")) {
            System.out.println("检测到百度相关标题，返回百度URL");
            return "https://www.baidu.com";
        } else if (lowerTitle.contains("youtube")) {
            System.out.println("检测到YouTube相关标题，返回YouTube URL");
            return "https://www.youtube.com";
        } else if (lowerTitle.contains("github")) {
            System.out.println("检测到GitHub相关标题，返回GitHub URL");
            return "https://github.com";
        } else if (lowerTitle.contains("bing")) {
            System.out.println("检测到Bing相关标题，返回Bing URL");
            return "https://www.bing.com";
        }
        
        System.out.println("无法从标题提取URL: " + title);
        return null;
    }
    
    /**
     * 获取当前页面内容（改进实现）
     * 通过获取浏览器窗口标题来检测搜索关键字
     */
    public static String getCurrentPageContent() {
        try {
            // 获取当前活动窗口标题
            String windowTitle = getCurrentActiveWindowTitle();
            if (windowTitle != null && !windowTitle.trim().isEmpty()) {
                // 检查是否是搜索页面
                String lowerTitle = windowTitle.toLowerCase();
                if (lowerTitle.contains("google") || lowerTitle.contains("baidu") || 
                    lowerTitle.contains("bing") || lowerTitle.contains("搜索") ||
                    lowerTitle.contains("search")) {
                    // 返回窗口标题作为页面内容，用于关键字检测
                    return windowTitle;
                }
            }
            
            // 如果不是搜索页面，返回空字符串
            return "";
        } catch (Exception e) {
            System.err.println("获取页面内容失败: " + e.getMessage());
            return "";
        }
    }
    
    /**
     * 获取当前活动窗口标题
     */
    private static String getCurrentActiveWindowTitle() {
        try {
            System.out.println("开始获取浏览器活动窗口标题...");
            
            // 只获取浏览器进程的活动窗口标题
            String[] browserProcesses = {"chrome", "firefox", "msedge", "iexplore", "opera", "safari"};
            
            for (String browserProcess : browserProcesses) {
                ProcessBuilder pb = new ProcessBuilder(
                    "powershell.exe", 
                    "-Command", 
                    "Get-Process " + browserProcess + " -ErrorAction SilentlyContinue | " +
                    "Where-Object {$_.MainWindowTitle -ne ''} | " +
                    "Select-Object -First 1 MainWindowTitle | " +
                    "ForEach-Object {$_.MainWindowTitle}"
                );
                
                Process process = pb.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
                
                String line;
                String result = "";
                while ((line = reader.readLine()) != null) {
                    String title = line.trim();
                    if (!title.isEmpty() && !title.contains("MainWindowTitle") && !title.contains("---")) {
                        System.out.println("找到" + browserProcess + "浏览器窗口标题: " + title);
                        result = title;
                        break;
                    }
                }
                
                process.waitFor();
                reader.close();
                
                if (!result.isEmpty()) {
                    System.out.println("最终返回的浏览器窗口标题: " + result);
                    return result;
                }
            }
            
            System.out.println("未找到任何浏览器活动窗口");
            return "";
        } catch (Exception e) {
            System.err.println("获取浏览器活动窗口标题失败: " + e.getMessage());
            e.printStackTrace();
            return "";
        }
    }
    
    /**
     * 检查浏览器是否正在运行
     */
    public static boolean isBrowserRunning() {
        try {
            ProcessBuilder pb = new ProcessBuilder(
                "powershell.exe", 
                "-Command", 
                "Get-Process chrome,msedge,firefox -ErrorAction SilentlyContinue | Measure-Object | Select-Object Count"
            );
            
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("Count")) {
                    continue;
                }
                try {
                    int count = Integer.parseInt(line.trim());
                    return count > 0;
                } catch (NumberFormatException e) {
                    // 忽略解析错误
                }
            }
            
            process.waitFor();
            reader.close();
            
        } catch (Exception e) {
            System.err.println("检查浏览器运行状态失败: " + e.getMessage());
        }
        
        return false;
    }
    
    /**
     * 关闭当前浏览器标签页
     * 支持Chrome、Firefox、Edge等主流浏览器
     */
    public static void closeCurrentTab() {
        try {
            System.out.println("正在关闭当前浏览器标签页...");
            
            // 方法1：使用更可靠的PowerShell脚本发送Ctrl+W
            boolean success = sendCtrlWCommand();
            
            if (!success) {
                System.out.println("方法1失败，尝试方法2...");
                // 方法2：使用WScript发送按键
                success = sendCtrlWViaWScript();
            }
            
            if (!success) {
                System.out.println("方法2失败，尝试方法3...");
                // 方法3：直接杀死特定浏览器标签页进程（仅Chrome）
                success = closeChromeBrowserTab();
            }
            
            if (success) {
                System.out.println("已成功关闭浏览器标签页");
            } else {
                System.err.println("所有关闭标签页的方法都失败了");
            }
            
        } catch (Exception e) {
            System.err.println("关闭浏览器标签页失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 方法1：使用PowerShell发送Ctrl+W快捷键
     */
    private static boolean sendCtrlWCommand() {
        try {
            // 检测并激活当前活动的浏览器窗口，然后发送Ctrl+W
            String[] browsers = {"Chrome", "Firefox", "Edge", "Internet Explorer", "Opera", "Safari"};
            
            for (String browser : browsers) {
                ProcessBuilder pb = new ProcessBuilder(
                    "powershell.exe", 
                    "-Command", 
                    "$wshell = New-Object -ComObject wscript.shell; " +
                    "if ($wshell.AppActivate('" + browser + "')) { " +
                    "Start-Sleep -Milliseconds 200; $wshell.SendKeys('^w'); exit 0 } else { exit 1 }"
                );
                
                Process process = pb.start();
                int exitCode = process.waitFor();
                
                if (exitCode == 0) {
                    System.out.println("成功激活" + browser + "浏览器并发送关闭命令");
                    return true;
                }
            }
            
            return false;
        } catch (Exception e) {
            System.err.println("PowerShell方法失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 方法2：使用WScript发送按键
     */
    private static boolean sendCtrlWViaWScript() {
        try {
            String[] browsers = {"Chrome", "Firefox", "Edge", "Internet Explorer", "Opera", "Safari"};
            
            for (String browser : browsers) {
                // 创建临时VBS脚本
                String vbsScript = "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\n" +
                                  "On Error Resume Next\n" +
                                  "result = WshShell.AppActivate(\"" + browser + "\")\n" +
                                  "If result Then\n" +
                                  "    WScript.Sleep 200\n" +
                                  "    WshShell.SendKeys \"^w\"\n" +
                                  "    WScript.Quit 0\n" +
                                  "Else\n" +
                                  "    WScript.Quit 1\n" +
                                  "End If";
                
                // 写入临时文件
                java.io.File tempFile = java.io.File.createTempFile("closeTab", ".vbs");
                try (java.io.FileWriter writer = new java.io.FileWriter(tempFile)) {
                    writer.write(vbsScript);
                }
                
                // 执行VBS脚本
                ProcessBuilder pb = new ProcessBuilder("cscript", "//NoLogo", tempFile.getAbsolutePath());
                Process process = pb.start();
                int exitCode = process.waitFor();
                
                // 删除临时文件
                tempFile.delete();
                
                if (exitCode == 0) {
                    System.out.println("VBS脚本成功激活" + browser + "浏览器并发送关闭命令");
                    return true;
                }
            }
            
            return false;
        } catch (Exception e) {
            System.err.println("VBS脚本方法失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 方法3：针对各种浏览器的进程处理
     */
    private static boolean closeChromeBrowserTab() {
        try {
            // 定义各种浏览器的进程名
            String[] browserProcesses = {"chrome", "firefox", "msedge", "iexplore", "opera", "safari"};
            
            for (String processName : browserProcesses) {
                ProcessBuilder pb = new ProcessBuilder(
                    "powershell.exe", 
                    "-Command", 
                    "$processes = Get-Process " + processName + " -ErrorAction SilentlyContinue; " +
                    "if ($processes) { " +
                    "$processes | ForEach-Object { " +
                    "Add-Type -AssemblyName System.Windows.Forms; " +
                    "[System.Windows.Forms.SendKeys]::SendWait('^w'); " +
                    "Start-Sleep -Milliseconds 100 }; " +
                    "exit 0 } else { exit 1 }"
                );
                
                Process process = pb.start();
                int exitCode = process.waitFor();
                
                if (exitCode == 0) {
                    System.out.println("成功向" + processName + "进程发送关闭标签页命令");
                    return true;
                }
            }
            
            return false;
        } catch (Exception e) {
            System.err.println("浏览器进程处理方法失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 强制关闭指定浏览器进程的当前标签页
     * 备用方案：如果快捷键方式失败，可以尝试这种方式
     */
    public static void forceCloseCurrentTab() {
        try {
            System.out.println("正在强制关闭当前浏览器标签页...");
            
            // 获取当前活动窗口并发送Alt+F4关闭命令
            ProcessBuilder pb = new ProcessBuilder(
                "powershell.exe", 
                "-Command", 
                "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('%{F4}')"
            );
            
            Process process = pb.start();
            process.waitFor();
            
            System.out.println("已发送强制关闭命令");
            
        } catch (Exception e) {
            System.err.println("强制关闭浏览器标签页失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}